<?php

	/**
	 * 
	 * @author bsuter
	 *
	 */
	Class Yomm_Library_Image {
		
		Public $db = null;
		
		Public $thumb = null;
		
		Public $error = null;
		
		Public $file_ids = array();
		
		Public Function __construct()
		{			
			$this->db = ydsql::getInstance();
			
			$this->thumb = new Yomm_Image_Thumb();
			
			$this->thumb->setSizes(array(
				"small" => SiteConfig::ImageResizeSmall,
				"portrait" => SiteConfig::ImageResizePortrait,
				"full" => SiteConfig::ImageResizeFull
			));
			
			$this->thumb->setSaveDir(Yomm_Config::DIR_IMAGES_PATH);
		}
		
		/**
		 * $_FILES array
		 * 
		 * @param $file_array [array] $_FILES['file_name']
		 */
		Public Function Upload($file_array)
		{
			
			$this->thumb->setImage($file_array['tmp_name'], strtolower(pathinfo($file_array['name'], PATHINFO_EXTENSION)));

			// start to convert given files!
			if($this->thumb->convert())
			{
				
				foreach($this->thumb->getFiles() as $file => $value)
				{
					$handler = $this->db->handler("image_lib", array(
						"name" => $value['name'],
						"mime" => $value['mime_type']
					), false, true);
					
					$this->file_ids[] = $handler;
					
					if($handler == false)
					{
						throw new Yomm_Error('error while saving image database entry');
						$this->error = "Fehler beim Speichern der Datenbank einträge";
						return false;
					}
				}
				
				if(count($this->file_ids) == 1)
				{
					return $this->file_ids[0];
				} else {
					return $this->file_ids;
				}
				
							
			} else {
				throw new Yomm_Error($this->thumb->error);
				$this->error = $this->thumb->error;
				return false;
			}
			
		}
		
		Static Public Function Show($image_id, $type = 'portrait')
		{
			if(empty($image_id)) return "no_image";
			
			$db = ydsql::getInstance();
			
			$obj = $db->select("image_lib", "*", "WHERE id='$image_id'", false);
			
			if(count($obj) == 0) return "no_image_existst";
			
			return SiteConfig::Domain . Yomm_Config::DIR_IMAGES_PATH . $obj->name . '_' . $type . '.' . $obj->mime;
		}
		
	}